import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import Layout from '../views/Layout.vue'
import Account from '../views/Layout/Account.vue'
// TODO: 导入商家token
// import { useUserStore } from '../stores/user';

// 懒加载账号管理子页面
const Profile = () => import('../views/account/Profile.vue')

// 路由配置类型
type AppRouteRecordRaw = RouteRecordRaw & {
  meta?: {
    title?: string
    requiresAuth?: boolean
  }
}

//定义路由关系
const routes: AppRouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/layout'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: { title: '注册', requiresAuth: false }
  },
  {
    path: '/layout',
    name: 'Layout',
    component: Layout,
    meta: { title: '首页', requiresAuth: false }
  },
  
  {
    path: '/account',
    name: 'Account',
    component: Account,
    redirect: '/account/profile',
    children: [
      {
        path: 'profile',
        name: 'Profile',
        component: Profile,
        meta: { title: '个人信息', requiresAuth: true }
      },
      {
        path: 'orders',
        name: 'Orders',
        component: () => import('../views/account/Profile.vue'), // 暂时复用Profile组件
        meta: { title: '订单', requiresAuth: true }
      },
      {
        path: 'favorites',
        name: 'Favorites',
        component: () => import('../views/account/Profile.vue'), // 暂时复用Profile组件
        meta: { title: '收藏', requiresAuth: true }
      },
      {
        path: 'wallet',
        name: 'Wallet',
        component: () => import('../views/account/Profile.vue'), // 暂时复用Profile组件
        meta: { title: '钱包', requiresAuth: true }
      },
      {
        path: 'address',
        name: 'Address',
        component: () => import('../views/account/Address.vue'),
        meta: { title: '地址', requiresAuth: true }
      },
      {
        path: 'coupons',
        name: 'Coupons',
        component: () => import('../views/account/Profile.vue'), // 暂时复用Profile组件
        meta: { title: '优惠券', requiresAuth: true }
      },
      {
        path: 'messages',
        name: 'Messages',
        component: () => import('../views/account/Profile.vue'), // 暂时复用Profile组件
        meta: { title: '消息', requiresAuth: true }
      },
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('../views/account/Profile.vue'), // 暂时复用Profile组件
        meta: { title: '设置', requiresAuth: true }
      }
    ]
  }, 
  {    
    path: '/cart',    
    name: 'Cart',    
    component: () => import('../views/cart/Cart.vue'),    
    meta: { title: '购物车', requiresAuth: true }  
  },  
  {    
    path: '/cart/order-confirm',    
    name: 'OrderConfirm',    
    component: () => import('../views/cart/OrderConfirm.vue'),    
    meta: { title: '订单确认', requiresAuth: true } 
   },
  {
    path: '/payment',
    name: 'Payment',
    component: () => import('../views/order/PaymentPage.vue'),
    meta: { title: '支付订单', requiresAuth: true }
  },
  {
    path: '/purchased-items',
    name: 'PurchasedItems',
    component: () => import('../views/order/PurchasedItems.vue'),
    meta: { title: '已买到的宝贝', requiresAuth: true }
  },
  {
    path: '/my-orders',
    name: 'MyOrders',
    component: () => import('../views/order/MyOrders.vue'),
    meta: { title: '我的订单', requiresAuth: true }
  },
  {
    path: '/product/:id',
    name: 'ProductDetail',
    component: () => import('../views/product/ProductDetail.vue'),
    meta: { title: '商品详情', requiresAuth: false }
  },
  {
    path: '/search',
    name: 'SearchResults',
    component: () => import('../views/product/SearchResults.vue'),
    meta: { title: '搜索结果', requiresAuth: false }
  },
  {
    path: '/support',
    name: 'Support',
    component: () => import('../views/support/Support.vue'),
    meta: { title: '帮助中心 & 支持一下', requiresAuth: false }
  },
  {
    path: '/admin',
    name: 'Admin',
    component: () => import('../views/Layout/AdminPanel.vue'),
    redirect: '/admin/orders',
    children: [
      {
        path: 'dashboard',
        redirect: '/admin/orders'
      },
      {
        path: 'orders',
        name: 'AdminOrders',
        component: () => import('../views/admin/Orders.vue'),
        meta: { title: '订单管理', requiresAuth: true }
      },
      { path: 'products', name: 'AdminProducts', component: () => import('../views/admin/Products.vue'), meta: { title: '商品管理', requiresAuth: true } },
      { path: 'stores', name: 'AdminStores', component: () => import('../views/admin/Stores.vue'), meta: { title: '商家管理', requiresAuth: true } },
      { path: 'users', name: 'AdminUsers', component: () => import('../views/admin/Users.vue'), meta: { title: '用户管理', requiresAuth: true } },
      { path: 'settings', name: 'AdminSettings', component: () => import('../views/admin/Settings.vue'), meta: { title: '系统设置', requiresAuth: true } }
    ]
  },
  {
    path: '/merchant/auth',
    name: 'MerchantAuth',
    component: () => import('../views/merchant/MerchantAuth.vue'),
    meta: { title: '商家登录/注册', requiresAuth: false }
  },
  {
    path: '/merchant/dashboard',
    name: 'MerchantDashboard',
    component: () => import('../views/merchant/MerchantDashboard.vue'),
    meta: { title: '店铺管理', requiresAuth: true }
  },
  {
    path: '/merchant/orders',
    name: 'MerchantOrders',
    component: () => import('../views/merchant/MerchantOrders.vue'),
    meta: { title: '订单管理', requiresAuth: true }
  },
  {
    path: '/merchant/profile',
    name: 'MerchantProfile',
    component: () => import('../views/merchant/MerchantProfile.vue'),
    meta: { title: '商家信息', requiresAuth: true }
  }
]
//创建路由器
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  console.log('from', from)
  // 获取用户权限, 控制是否允许访问
  try {
    import('../stores/user').then(({ useUserStore }) => {
      const userStore = useUserStore()
      // 需要登录的页面：统一在业务里拦截401；此处只做管理员路由的角色校验
      if (to.path.startsWith('/admin')) {
        if (!userStore.isLoggedIn || !userStore.isAdmin) {
          return next({ name: 'Login' })
        }
      }
      next()
    }).catch(() => {
      // 若 store 尚未就绪，不阻塞导航
      next()
    })
  } catch (e) {
    // 若 store 尚未就绪，不阻塞导航
    next()
  }

  // if (to.meta?.requiresAuth && !useUserStore().是否商家) {
  //   // 如果需要登录权限，并且用户未登录，则跳转到登录页面
  //   next({name: '商家登录页面'})
  // }

  // 设置页面标题
  if (to.meta?.title) {
    document.title = `${to.meta.title} - 宝可得`
  }
  next()
})

export default router